package mysql

import (
	"gorm.io/gorm/clause"

	"mxshop_srvs/goods_srv/model"
	proto "mxshop_srvs/goods_srv/proto/gen/v1"
	mql "mxshop_srvs/shared/mysql"
)

func (g *Gorm) CreateBanner(bannerReq *proto.BannerRequest) (int32, error) {
	var banner = model.Banner{
		BaseModel: model.BaseModel{
			ID:        mql.NewObjID,
			CreatedAt: mql.CreatedAt(),
		},
		Image: bannerReq.Image,
		Url:   bannerReq.Url,
		Index: bannerReq.Index,
	}
	return banner.ID, g.db.Create(&banner).Error
}

func (g *Gorm) GetBanner(bannerID int32) (banner model.Banner, err error) {
	return banner, g.db.First(&banner, bannerID).Error
}

func (g *Gorm) GetBannerList() ([]model.Banner, int32, error) {
	var banners []model.Banner
	result := g.db.Find(&banners)
	return banners, int32(result.RowsAffected), result.Error
}

func (g *Gorm) UpdateBanner(banner model.Banner, req *proto.BannerRequest) (model.Banner, int64, error) {
	result := g.db.Model(&banner).Clauses(clause.Returning{}).Updates(model.Banner{
		Image: req.Image,
		Url:   req.Url,
		Index: req.Index,
	})
	if err := result.Error; err != nil {
		return model.Banner{}, 0, err
	}
	return banner, result.RowsAffected, nil
}

func (g *Gorm) DeleteBanner(req *proto.BannerRequest) (int64, error) {
	result := g.db.Delete(&model.Banner{}, req.Id)
	return result.RowsAffected, result.Error
}
